<?php

class Damages_Methods_Request_Edit_ProcessPermissions extends Damages_Methods_Request {

  /**
   *
   * @var Damages_Methods_Data_Permission_Edit[]
   */
  public $permissions = array();

  public function __construct($params) {
    parent::__construct($params);
    foreach ($params->permissions->toArray() as $permission) {
      $permissionObj = new Damages_Methods_Data_Permission_Edit($permission);
      $permissionObj->setProcessTypes($permission);
      $this->permissions[] = $permissionObj;
    }
  }

  /**
   * 
   * @return Damages_Methods_Response_GetPermissionManagmentData
   * @throws Exception
   */
  public function process() {
    $con = Propel::getConnection(Damages_Config::getInstance()->datasource);
    $adminId = DamagesPermissionsQuery::create()->filterByCode('ADM')->findOne()->getId();
    $con->beginTransaction();
    try {
      DamagesProcessTypePermissionsQuery::create()->filterByPermissionId($adminId, Criteria::NOT_EQUAL)->delete();
      foreach ($this->permissions as $permission) {
        foreach ($permission->processes as $process) {
          $processTypePermission = new DamagesProcessTypePermissions();
          $processTypePermission->setProcessTypeId($process->id);
          $processTypePermission->setPermissionId($permission->id);
          $processTypePermission->save();
          foreach ($process->actions as $action) {
            $processTypeActionPermission = new DamagesProcessTypeActionsPermissions();
            $processTypeActionPermission->setProcessTypeId($process->id);
            $processTypeActionPermission->setPermissionId($permission->id);
            $processTypeActionPermission->setActionId($action->id);
            $processTypeActionPermission->save();
          }
        }
      }
      // TODO: weryfikacja: walidacja - wyszukaj akcje przypisane do procesu a nie przypisane do roli
      $this->validateActionsPermissions();
      $con->commit();
    } catch (Exception $exc) {
      $con->rollBack();
      throw $exc;
    }

    $response = new Damages_Methods_Response_GetPermissionManagmentData(true);
    $response->setPermissions();
    return $response;
  }

  private function validateActionsPermissions() {
    $missingData = DamagesProcessTypeActionsQuery::create()
            ->useProcessTypeActionsPermissionsQuery(null, Criteria::LEFT_JOIN)
            ->filterByPermissionId(null)
            ->endUse()
            ->find();
    if (!$missingData->isEmpty())
      throw new Damages_Exception_App(Damages_Codes::INVALID_ACTIONS_PERMISSIONS);
    return true;
  }

}